/*
 * @(#)JSONUtil.java        1.0 2010-6-26
 *
 * Copyright (c) 2010 SunYard System Engineering CoLtd.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of 
 * SunYard System Engineering CoLtd. ("Confidential Information").  
 * You shall not disclose such Confidential Information and shall use it 
 * only in accordance with the terms of the license agreement you entered 
 * into with SunYard.
 */
package org.xukai.common.util;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * JSONUTil
 * @author YED
 * */
public final class JSONUtil {
	/**
	 * 把HashMap中的数据转换成JSON数据
	 * 用于查看具体的一张业务工单
	 * 也就是要满足ExtJs是Form.load的参数格式
	 */
	public static String oneHmToJson(HashMap<String, Object> data) {
		StringBuffer json = new StringBuffer(200);
		json.append("{success:true,data:[");
		if (data != null && data.size() > 0) {
			String key = null;
			for(Entry<String, Object> rowEntry:data.entrySet()){
				key = rowEntry.getKey();
				json.append(key).append(":\"").append(
						convertNull(rowEntry.getValue())).append("\",");
			}
			json.deleteCharAt(json.length() - 1);
		}
		json.append("]}");
		return json.toString();
	}
	
	/**
	 * 将HASHMAP转为JSON数据格式
	 * @param map
	 * @return JSON数据
	 */
	 public static String hashMapToJson(HashMap map) {  
	        String string = "{";  
	        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {  
	            Entry e = (Entry) it.next();  
	            string += "'" + e.getKey() + "':";  
	            string += "'" + e.getValue() + "',";  
	        }  
	        string = string.substring(0, string.lastIndexOf(","));  
	        string += "}";  
	        return string;  
	    }  

	


	/**
	 * null值转空值
	 */
	private static String convertNull(Object data) {
		return data == null ? "" : data.toString();
	}

	/**
	 * 把List中的Object数据转换成JSON数据
	 * 用于处理多条记录
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public static String listObjectToJSON(List<Object> rows,String total) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		StringBuffer json = new StringBuffer(400);
		json.append("{total:");
		json.append(total);
		json.append(",rows:[");
		if (rows != null && rows.size() > 0) {
			Object row = null;
			for (int i = 0, len = rows.size(); i < len; i++) {
				row = rows.get(i);				
				HashMap<String, Object> hsrow = (HashMap<String, Object>) row;
				json.append("{");
				String key = null;
				for(Entry<String,Object> rowEntry:hsrow.entrySet()){
					key = rowEntry.getKey();
					json.append(key);
					json.append(":\"");
					json.append(convertNull(rowEntry.getValue()));
					json.append("\",");
				}
				json.deleteCharAt(json.length() - 1);
				json.append("},");
			}
			json.deleteCharAt(json.length() - 1);
		}
		json.append("]}");
		return json.toString();
	}
	/**
	 * 把List中的HashMap数据转换成JSON数据
	 * 用于处理多条记录
	 */
	public static String listMapToJSON(List<HashMap<String, Object>> rows) {
		StringBuffer json = new StringBuffer(400);
		json.append("{total:");
		if(rows != null){
			json.append(rows.size());
		}else{
			json.append("0");
		}
		json.append(",rows:[");
		if (rows != null && rows.size() > 0) {
			HashMap<String, Object> row = null;
			for (int i = 0, len = rows.size(); i < len; i++) {
				row = rows.get(i);
				json.append("{");
				String key = null;
				for(Entry<String, Object> rowEntry:row.entrySet()){
					key = rowEntry.getKey();
					json.append(key);
					json.append(":\"");
					json.append(convertNull(rowEntry.getValue()));
					json.append("\",");
				}
				json.deleteCharAt(json.length() - 1);
				json.append("},");
			}
			json.deleteCharAt(json.length() - 1);
		}
		json.append("]}");
		return json.toString();
	}

	/**
	 * 把List中的HashMap数据转换成JSON数据
	 * 用于处理多条记录
	 */
	public static String listsToJSON(List<HashMap<String, Object>> rows,
			int allLength) {

		StringBuffer json = new StringBuffer(400);
		json.append("{total:");
		json.append(allLength);
		json.append(",rows:[");
		if (rows != null && rows.size() > 0) {
			HashMap<String, Object> row = null;
			for (int i = 0, len = rows.size(); i < len; i++) {
				row = rows.get(i);
				json.append("{");
				String key = null;
				for(Entry<String, Object> rowEntry : row.entrySet()){
					key = rowEntry.getKey();
					json.append(key);
					json.append(":\"");
					json.append(convertNull(rowEntry.getValue()));
					json.append("\",");
				}
				json.deleteCharAt(json.length() - 1);
				json.append("},");
			}
			json.deleteCharAt(json.length() - 1);
		}
		json.append("]}");
		return json.toString();
	}

	/**
	 * 转换ExtJs识别JSON树
	 */
	public static String extjsTree(List<HashMap<String, Object>> rows) {

		StringBuffer json = new StringBuffer(100);
		json.append("[");

		if (rows != null && rows.size() > 0) {
			HashMap<String, Object> row = null;
			for (int i = 0, len = rows.size(); i < len; i++) {
				row = rows.get(i);
				json.append("{id:").append(row.get("ID")).append(",");
				json.append("text:\"").append(row.get("TEXT")).append("\",");
				json.append("leaf:true,");
				json.append("key:\"").append(row.get("QTIP")).append("\"},");
			}
		}
		json.deleteCharAt(json.length() - 1);
		json.append("]");
		return json.toString();
	}

	/**
	 * 转换ExtJs识别JSON树
	 */
	public static String groupTree(List<HashMap<String, Object>> rows) {

		StringBuffer json = new StringBuffer(100);
		json.append("[");

		if (rows != null && rows.size() > 0) {
			HashMap<String, Object> row = null;
			for (int i = 0, len = rows.size(); i < len; i++) {
				row = rows.get(i);
				json.append("{id:").append(row.get("ID")).append(",");
				json.append("key:\"").append(row.get("KEY")).append("\",");
				if (((String) row.get("ISSELECTED")).equals("1")) {
					json.append("checked:false,");
				}
				json.append("oflag:").append(row.get("OFLAG")).append(",");
				json.append("text:\"").append(row.get("TEXT")).append("\"");
				json.append(",pinyin:\"").append(row.get("PINYIN")).append("\"");
				if (row.get("LEAF") != null) {
					json.append(",leaf:").append(row.get("LEAF"));
				}
				json.append("},");
			}
		}

		json.deleteCharAt(json.length() - 1);
		json.append("]");
		return json.toString();
	}
	/**
	 * JSON格式数据转换为集合
	 */
	public static HashMap<String, String> jsonToHashMap(String json) {

		HashMap<String, String> oneData = null;

		char first = json.charAt(0);

		char last = json.charAt(json.length() - 1);

		if (first == '{' && last == '}') {
			//去掉{}
			json = trimQu(json);
			String[] params = json.split(",");
			oneData = new HashMap<String, String>();
			String[] hm = null;
			for (int i = 0, len = params.length; i < len; i++) {
				hm = params[i].split(":");
				oneData.put(trimQu(hm[0]), trimQu(hm[1]));
			}
		}
		return oneData;
	}

	/**
	 * 去掉字符串的第一个和最后一个字符
	 */
	private static String trimQu(String s) {
		s = (s != null && s.length() > 2) ? s.substring(1, s.length() - 1) : "";
		return s;
	}

	/**
	 * 过滤特殊字符
	 */
	public static String quote(String string) {
		if (string == null || string.length() == 0) {
			return "\"\"";
		}
		char b;
		char c = 0;
		int i;
		int len = string.length();
		StringBuffer sb = new StringBuffer(len + 4);
		String t;

		sb.append('"');
		for (i = 0; i < len; i += 1) {
			b = c;
			c = string.charAt(i);
			switch (c) {
			case '\\':
			case '"':
				sb.append('\\');
				sb.append(c);
				break;
			case '/':
				if (b == '<') {
					sb.append('\\');
				}
				sb.append(c);
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\r':
				sb.append("\\r");
				break;
			default:
				if (c < ' ') {
					t = "000" + Integer.toHexString(c);
					sb.append("\\u" + t.substring(t.length() - 4));
				} else {
					sb.append(c);
				}
			}
		}
		sb.append('"');
		return sb.toString();
	}
	
	/**
	 * 返回json格式的错误信息
	 * */
	public static String errorInjson(String errorCode,String returnCode,String errorInfo) {
		   
		return "{\"result\": \"['"+errorCode+"','"+returnCode+"','"+errorInfo+"']\"}" ;
	}

	/**
	 * 把List中的HashMap数据转换成JSON数据
	 * 用于处理多条记录
	 */
	public static String listMapToARR(List<Object> rows,  String tagname) {
		StringBuffer json = new StringBuffer(400);
		json.append(tagname);
		json.append(":[");
		if (rows != null && rows.size() > 0) {
			HashMap<String, Object> row = null;
			for (int i = 0, len = rows.size(); i < len; i++) {
				row = (HashMap<String, Object>)rows.get(i);
				json.append("{");
				String key = null;
				for(Entry<String, Object> rowEntry:row.entrySet()){
					key = rowEntry.getKey();
					json.append(key);
					json.append(":\"");
					json.append(convertNull(rowEntry.getValue()));
					json.append("\",");
				}
				json.deleteCharAt(json.length() - 1);
				json.append("},");
			}
			json.deleteCharAt(json.length() - 1);
		}
		json.append("]");
		return json.toString();
	}

	
	public static void main(String[] args) {

	}
}
